<template>
  <div>
    <el-form-item label="执行类型" key="executeType">
      <el-select v-model="serviceTaskForm.executeType">
        <el-option label="Java类" value="class" />
        <el-option label="表达式" value="expression" />
        <el-option label="代理表达式" value="delegateExpression" />
      </el-select>
    </el-form-item>
    <el-form-item
      v-if="serviceTaskForm.executeType === 'class'"
      label="Java类"
      prop="class"
      key="execute-class"
    >
      <el-input v-model="serviceTaskForm.class" clearable @change="updateElementTask" />
    </el-form-item>
    <el-form-item
      v-if="serviceTaskForm.executeType === 'expression'"
      label="表达式"
      prop="expression"
      key="execute-expression"
    >
      <el-input v-model="serviceTaskForm.expression" clearable @change="updateElementTask" />
    </el-form-item>
    <el-form-item
      v-if="serviceTaskForm.executeType === 'delegateExpression'"
      label="代理表达式"
      prop="delegateExpression"
      key="execute-delegate"
    >
      <el-input v-model="serviceTaskForm.delegateExpression" clearable @change="updateElementTask" />
    </el-form-item>
  </div>
</template>

<script setup name="ServiceTask">

const {proxy} = getCurrentInstance()

const props = defineProps({
  id: String,
  type: String
})
const {id,type} = toRefs(props)
const state = reactive({
  defaultTaskForm: {
    executeType: "",
    class: "",
    expression: "",
    delegateExpression: ""
  },
  serviceTaskForm: {},
  bpmnElement: undefined
})
const {defaultTaskForm,serviceTaskForm} = toRefs(state)

watch(()=>props.id,() => {
  state.bpmnElement = window.bpmnInstances.bpmnElement;
  proxy.$nextTick(() => resetTaskForm());
}, { immediate: true })

function resetTaskForm() {
  for (let key in state.defaultTaskForm) {
    let value = state.bpmnElement?.businessObject[key] || state.defaultTaskForm[key];
    if (value) {
      state.serviceTaskForm.executeType = key
    }
    state.serviceTaskForm.key = value
  }
}
function updateElementTask() {
  let taskAttr = Object.create(null);
  const type = state.serviceTaskForm.executeType;
  for (let key in state.serviceTaskForm) {
    if (key !== 'executeType' && key !== type) taskAttr[key] = null;
  }
  taskAttr[type] = state.serviceTaskForm[type] || "";
  window.bpmnInstances.modeling.updateProperties(toRaw(state.bpmnElement), taskAttr);
}

onUnmounted(() => {
  state.bpmnElement = null;
})

</script>
